// 两根线
// 同步：组件 commit -> mutations -> state
// 异步： 组件 dispatch -> actions -> commit -> mutations -> state
import { getToken, setToken, removeToken } from '@/utils/storage'
import { login } from '@/api/user'

export default {
  // 开启命名空间
  namespaced: true,
  // 放数据的地方
  state: {
    token: getToken() || null
  },
  // 相当于组件中计算属性
  getters: {},
  // 这个是唯一修改state中数据地方
  mutations: {
    // setCount(state) {}
    setToken (state, payload) {
      // console.log(payload)
      state.token = payload
      setToken(payload)
      // console.log(state.token)
    },
    removeToken (state) {
      state.token = null
      removeToken()
    }
  },
  // 写异步的ajax的地方
  actions: {
    async login (store, payload) {
      // console.log(payload)
      // const res = JSON.parse(payload)
      const res = await login(payload)
      store.commit('setToken', res.data.data)
    },
    logout (store) {
      store.commit('removeToken')
    }
  }
}
